package com.gidgabs.common.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

import static java.time.temporal.ChronoUnit.MINUTES;

/**
 * 日期处理
 */
public class DateUtils {

    /**
     * 时间格式 年 (yyyy)
     */
    public final static String DATE_YEARS = "yyyy";

    /**
     * 时间格式 月 (MM)
     */
    public final static String DATE_MONTH = "MM";
    /**
     * 时间格式(yyyy-MM-dd)
     */
    public final static String DATE_PATTERN = "yyyy-MM-dd";
    /**
     * 时间格式(yyyy-MM-dd HH:mm:ss)
     */
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static String format(Date date) {
        return format(date, DATE_PATTERN);
    }

    public static String format(Date date, String pattern) {
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }

    /**
     * 字符串转date
     * @param dates
     * @return
     * @throws ParseException
     */
    public static Date toDate(String dates) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat(DATE_PATTERN);
        return df.parse(dates);
    }
    /**
     * 字符串转date
     * @param dates
     * @param pattern 格式
     * @return
     * @throws ParseException
     */
    public static Date toDate(String dates, String pattern) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat(pattern);
        return df.parse(dates);
    }

    //判断是否超过24小时
    public static boolean jisuan(String date1, String date2) throws Exception {
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-M-d HH:mm:ss");
        Date start = sdf.parse(date1);
        Date end = sdf.parse(date2);
        long cha = end.getTime() - start.getTime();
        double result = cha * 1.0 / (1000 * 60 * 60);
        if (result <= 24) {
            //System.out.println("可用");
            return true;
        } else {
            //System.out.println("已过期");
            return false;
        }
    }

    /**
     * 给时间加上几个小时
     * @param day 当前时间 格式：yyyy-MM-dd HH:mm:ss
     * @param hour 需要加的时间
     * @return
     */
    public static String addDateMinut(String day, int hour){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(day);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (date == null)
            return "";
        System.out.println("front:" + format.format(date)); //显示输入的日期
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.HOUR, hour);// 24小时制
        date = cal.getTime();
        System.out.println("after:" + format.format(date));  //显示更新后的日期
        cal = null;
        return format.format(date);

    }

    /**
     * 获取当前日期是是当前年的第几周
     * @return
     */
    public static int getWeek(){
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(new Date());
        return  calendar.get(Calendar.WEEK_OF_YEAR);
    }

    /**
     * 获取当前月
     * @return
     */
    public static int getMonth(){
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH )+1;
        return month;
    }

    /**
     * 获取当前年
     * @return
     */
    public static int getYear(){
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        return year;
    }


    /**
     * 获取两个时间相差的天数
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @return
     */
    public static Long getDaysBetween(Date startDate, Date endDate) {
        Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(startDate);
        fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
        fromCalendar.set(Calendar.MINUTE, 0);
        fromCalendar.set(Calendar.SECOND, 0);
        fromCalendar.set(Calendar.MILLISECOND, 0);

        Calendar toCalendar = Calendar.getInstance();
        toCalendar.setTime(endDate);
        toCalendar.set(Calendar.HOUR_OF_DAY, 0);
        toCalendar.set(Calendar.MINUTE, 0);
        toCalendar.set(Calendar.SECOND, 0);
        toCalendar.set(Calendar.MILLISECOND, 0);

        return (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24);
    }

    /**
     * 获取两个时间相差的天数
     * @param one 时间参数 1：
     * @param two 时间参数 2：
     * @return 相差天数
     */
    public static long getDistanceDays(String str1, String str2) throws Exception{
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date one;
        Date two;
        long days=0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff ;
            if(time1<time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            days = diff / (1000 * 60 * 60 * 24);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

//    public static void main(String[] agrs) throws Exception {
//        String dateString = "2018-05-30";
//
////        System.out.println(getDaysBetween(toDate(dateString),new Date()));
//        System.out.println(getDistanceDays(dateString,"2018-05-18"));
//    }


    public static Date todayStart(){
        LocalDate localDate = LocalDate.now();
        ZoneId zone = ZoneId.systemDefault();

        Instant instant = localDate.atStartOfDay(zone).toInstant();
        return  Date.from(instant);
    }
    public static Date todayEnd(){
        LocalDate localDate=LocalDate.now();
        LocalDateTime localDateTime = localDate.atTime(23, 59,59);

        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }
    public static Date dayEnd(Date date){
        Objects.requireNonNull(date,"时间参数不能为空");
        Instant instant = date.toInstant();
        LocalDateTime localDateTime=LocalDateTime.ofInstant(instant,ZoneId.systemDefault());
        LocalTime localTime=LocalTime.of(23,59,0);
        return Date.from(localDateTime.with(localTime).atZone(ZoneId.systemDefault()).toInstant());
    }
    public static Date dayStart(Date date){
        Objects.requireNonNull(date,"时间参数不能为空");
        Instant instant = date.toInstant();
        LocalDateTime localDateTime=LocalDateTime.ofInstant(instant,ZoneId.systemDefault());
        LocalTime localTime=LocalTime.of(0,0,0);
        return Date.from(localDateTime.with(localTime).atZone(ZoneId.systemDefault()).toInstant());
    }
    /**
     * 计算几天之前的时间
     * @param expiredDay
     * @return
     */
    public static Date preDay(Integer expiredDay) {
        LocalDateTime localDateTime=LocalDateTime.now();
        Instant instant = localDateTime.minusDays(expiredDay).atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }
    public static String dateFormart(Date date,String pattern){
        Objects.requireNonNull(date,"时间参数不能为空");
        Objects.requireNonNull(pattern,"时间格式正则不能为空");
        Instant instant = date.toInstant();
        LocalDateTime localDateTime=LocalDateTime.ofInstant(instant,ZoneId.systemDefault());
        return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
    }

    public static Date yearStart(Integer yearNum){
        Year year = Year.of(yearNum);
        Instant instant = year.atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

    public static Date yearEnd(Integer yearNum){
        Year year = Year.of(yearNum+1);
        Instant instant = year.atDay(1).atStartOfDay(ZoneId.systemDefault()).minusSeconds(1).toInstant();
        return Date.from(instant);
    }
    public static Date monthStart(Integer yearNum,Integer montyNum){
        Instant instant = LocalDate.of(yearNum, montyNum, 1).atStartOfDay(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }
    public static Date monthEnd(Integer yearNum,Integer montyNum){
        Instant instant =null;
        if (montyNum==12) instant=LocalDate.of(yearNum, montyNum, 31).atTime(23,59,59).atZone(ZoneId.systemDefault()).toInstant();
        else instant = LocalDate.of(yearNum, montyNum+1, 1).atStartOfDay(ZoneId.systemDefault()).minusSeconds(1).toInstant();
        return Date.from(instant);
    }

    public static LocalTime convertTime(Date time){
        return convertLocalDateTime(time).toLocalTime();
    }

    public static LocalDateTime convertLocalDateTime(Date time){
        Instant instant = time.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        return  LocalDateTime.ofInstant(instant, zone);
    }

    /**
     * 时间的加减计算
     * @param time
     * @param startrun
     * @return
     */
    public static Date calculateMin(Date time, Integer startrun,TemporalUnit temporalUnit) {
        LocalDateTime localDateTime = convertLocalDateTime(time);
        LocalDateTime result = localDateTime.plus(startrun, temporalUnit);
        Instant instant = result.atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

    /**
     * 将时间差秒,转换成 适当得日,时,分,秒差
     * @param seconds
     * @return
     */
    public static String betweenTimeToString(long seconds){
        long day_second=60*60*24;
        long hour_second=60*60;
        long minute_second=60;
        String day=null,hour=null,minute=null;
        if (seconds>day_second){
            long dayNum = seconds / day_second;
            day=String.valueOf(dayNum);
            seconds=seconds-day_second*dayNum;
        }if (seconds>hour_second){
            long hourNum = seconds / hour_second;
            hour=String.valueOf(hourNum);
            seconds=seconds-hourNum*hour_second;
        }if (seconds>minute_second){
            long minNum=seconds/minute_second;
            minute=String.valueOf(minNum);
            seconds=seconds-minNum*minute_second;
        }
        String result="";

        if (day!=null){
            result+=day+"天";
        }if (hour!=null)
            result+=hour+"小时";
        if (minute!=null)
            result+=minute+"分钟";
        result+=seconds+"秒";
        return result;
    }

    public static Date afterDay(int i) {
        LocalDateTime localDateTime=LocalDateTime.now();
        Instant instant = localDateTime.plusDays(i).atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

    /**
     * 往前 x 小时
     * @param clubRequestExpired
     * @return
     */
    public static Date preHours(Integer clubRequestExpired) {
        LocalDateTime localDateTime=LocalDateTime.now();
        Instant instant = localDateTime.minusHours(clubRequestExpired).atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }
    /**
     * 往后 x 小时
     * @param hours
     * @return
     */
    public static Date afterHours(Integer hours) {
        LocalDateTime localDateTime=LocalDateTime.now();
        Instant instant = localDateTime.plusHours(hours).atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }
    /**
     * 往后 x 分钟
     * @param minutes
     * @return
     */
    public static Date afterMinutes(Integer minutes) {
        LocalDateTime localDateTime=LocalDateTime.now();
        Instant instant = localDateTime.plusMinutes(minutes).atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

    public static Date afterMinutes(Date createTime, int minutes) {
        Instant instant = createTime.toInstant();
        Instant instantAfter = instant.plus(minutes, MINUTES);

        return Date.from(instantAfter);
    }

    public static Date preMinutes(Date createTime, int minutes) {
        Instant instant = createTime.toInstant();
        Instant instantAfter = instant.minus(minutes, MINUTES);

        return Date.from(instantAfter);
    }
}
